package cool.taomu.toolkit.stock.service

import com.google.inject.Inject
import cool.taomu.toolkit.annotations.httpclient.HttpClient
import cool.taomu.toolkit.rhino.Rhino
import cool.taomu.toolkit.script.IScript
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
import org.apache.commons.io.IOUtils
import org.apache.commons.vfs2.FileSystemManager
import org.slf4j.LoggerFactory

@HttpClient("http://hq.stock.sohu.com")
@Path("/cn")
interface IPkService {

    @GET
    @Produces(MediaType.TEXT_HTML)
    @Path("/{mcode}/{page}")
    def String getStock(@PathParam("mcode") String code, @PathParam("page") String page);
}

class PkService {
    val static LOG = LoggerFactory.getLogger(PkService);
    @Inject
    IPkService pk;

    @Inject
    @Rhino
    IScript script

    @Inject
    FileSystemManager fsManager

    def getData(String code) {
        var end3 = code.substring(6)
        try
            (var fobject =  fsManager.resolveFile("res://static/fortune_hq.js")) {
            var stext = IOUtils.toString(fobject.content.inputStream, "UTF-8")
            var htmlPage = #["cn_", code.replace("sh.", "").replace("sz.", ""), "-1.html"].join("")
            var scriptData = pk.getStock(end3, htmlPage)
            LOG.debug("stext:{}", stext)
            var result = script.execute(stext + "\n function a(){ return " + scriptData + "}", null, "a", null)
            LOG.debug("pk:{}",result)
            return result
        }
    }

}
